﻿using FluentValidation;
using WarehouseManagementSystem.DAL;
using WarehouseManagementSystem.Entities;

namespace WarehouseManagementSystem.Validators;

public class MemberValidator : AbstractValidator<Member>
{
    private readonly MemberRepository _memberRepository;

    public MemberValidator(MemberRepository memberRepository)
    {
        _memberRepository = memberRepository;

        RuleFor(x => x.Name).NotEmpty().MustAsync(IsExist).WithMessage("Name is not exist, please check your input");
        RuleFor(x => x.Password).NotEmpty().MustAsync(IsPasswordValid).WithMessage("Password is not valid");
    }

    private async Task<bool> IsExist(string name, CancellationToken cts) 
        => (await _memberRepository.FindAll(name)).Any();

    private async Task<bool> IsPasswordValid(string password, CancellationToken cts)
        => (await _memberRepository.GetAll()).Any(x => x.Password == password);

}